package network

import (
	"fmt"
	"gitee.com/amoyx/cloud-provider/pkg/cloud/aliyun/models"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	vpc20160428 "github.com/alibabacloud-go/vpc-20160428/v6/client"
)

type VSwitchGreeter interface {
	VSwitch(region string) VSwitchInterface
}

type VSwitchInterface interface {
	Create(args models.VSwitchRequest) (vswitchId string, err error)
	Delete(id string) (err error)
	Describe(id string) (result models.VSwitchResponse, err error)
}

type vswitch struct {
	config *openapi.Config
	region string
	client *vpc20160428.Client
}

func newVSwitch(network *Network, region string) VSwitchInterface {
	v := &vswitch{
		config: network.config,
		region: region,
	}
	endpoint := fmt.Sprintf("vpc.%s.aliyuncs.com", region)
	v.config.Endpoint = tea.String(endpoint)
	_client, _ := vpc20160428.NewClient(v.config)
	v.client = _client
	return v
}

// Create 创建交换机
func (w *vswitch) Create(args models.VSwitchRequest) (vswitchId string, err error) {
	request := &vpc20160428.CreateVSwitchRequest{
		RegionId:    tea.String(w.region),
		CidrBlock:   tea.String(args.CidrBlock),
		ZoneId:      tea.String(args.ZoneId),
		VpcId:       tea.String(args.VpcId),
		Description: tea.String(args.Description),
		VSwitchName: tea.String(args.VSwitchName),
	}
	runtime := &util.RuntimeOptions{}
	response, err := w.client.CreateVSwitchWithOptions(request, runtime)
	if err != nil {
		return
	}
	vswitchId = *response.Body.VSwitchId
	return
}

// Delete 删除交换机
func (w *vswitch) Delete(id string) (err error) {
	request := &vpc20160428.DeleteVSwitchRequest{
		RegionId:  tea.String("cn-shanghai"),
		VSwitchId: tea.String("id"),
	}
	runtime := &util.RuntimeOptions{}
	_, err = w.client.DeleteVSwitchWithOptions(request, runtime)
	return
}

// Describe 获取交换机详情
func (w *vswitch) Describe(id string) (result models.VSwitchResponse, err error) {
	request := &vpc20160428.DescribeVSwitchAttributesRequest{
		RegionId:  tea.String(w.region),
		VSwitchId: tea.String(id),
	}
	runtime := &util.RuntimeOptions{}
	response, err := w.client.DescribeVSwitchAttributesWithOptions(request, runtime)
	if err != nil {
		return
	}
	body := response.Body
	result = models.VSwitchResponse{
		VSwitchId:               *body.VSwitchId,
		VpcId:                   *body.VpcId,
		CidrBlock:               *body.CidrBlock,
		ZoneId:                  *body.ZoneId,
		AvailableIpAddressCount: *body.AvailableIpAddressCount,
		Description:             *body.Description,
		Status:                  *body.Status,
		VSwitchName:             *body.VSwitchName,
		CreationTime:            *body.CreationTime,
		IsDefault:               *body.IsDefault,
		RouteTable:              *body.RouteTable.RouteTableId,
	}
	return
}
